//统计一个数字在排序数组中出现的次数。 
//
// 
//
// 示例 1: 
//
// 
//输入: nums = [5,7,7,8,8,10], target = 8
//输出: 2 
//
// 示例 2: 
//
// 
//输入: nums = [5,7,7,8,8,10], target = 6
//输出: 0 
//
// 
//
// 提示： 
//
// 
// 0 <= nums.length <= 105 
// -109 <= nums[i] <= 109 
// nums 是一个非递减数组 
// -109 <= target <= 109 
// 
//
// 
//
// 注意：本题与主站 34 题相同（仅返回值不同）：https://leetcode-cn.com/problems/find-first-and-last-
//position-of-element-in-sorted-array/ 
// Related Topics 数组 二分查找 
// 👍 194 👎 0


package leetcode.editor.cn1;

//Java：在排序数组中查找数字 I

/**
 * 统计一个数字在排序数组中出现的次数。
 * nums 是一个非递减数组
 * <p>
 * 输入: nums = [5,7,7,8,8,10], target = 8
 * 输出: 2
 */
public class ZaiPaiXuShuZuZhongChaZhaoShuZiLcof {
    public static void main(String[] args) {
        Solution solution = new ZaiPaiXuShuZuZhongChaZhaoShuZiLcof().new Solution();
        // TO TEST
        System.out.println(solution.search(new int[]{5,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,10}, 8));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int search(int[] nums, int target) {
            return recur(nums, 0, nums.length-1, target);
        }

        public int recur(int[] nums, int lo, int hi, int target) {
            if (lo > hi) {
                return 0;
            }
            int mid = -1, count = 0;
            while (lo <= hi) {
                mid = (lo + hi) / 2;
                if (nums[mid] > target) {
                    hi = mid - 1;
                } else if (nums[mid] < target) {
                    lo = mid + 1;
                } else {
                    count = count + 1;
                    break;
                }
            }
            // 计算左边的数组
            count = count + recur(nums, lo,mid-1, target);
            // 计算右边的数组
            count = count + recur(nums, mid+1, hi, target);
            return count;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
